// 3、将本文件实现为一个中间件，以便在app.js中可以直接注册使用
'use strict'

let fs = require('fs');
let path = require('path');
let router = require('koa-router')();

function fillrouter(dir) {
    // 2、需要过滤真正的控制器文件（是js文件，并且不是index.js）
    let fill = fs.readdirSync(dir);       //读取根目录
    
    //筛选
    let fillpath = fill.filter((fillname) => {
        return fillname.endsWith('.js') && fillname != 'index.js';
    })
    return fillpath;
}

//注册路由
function registerRouter(fill) {
    fill.forEach(item => {
        let fillPath = path.join(__dirname, item);  //拼接根目录路径和js文件路径
        let filrouter = require(fillPath);        //获取路由

        //遍历循环路由，i表示js文件下暴露文件的键值对
        for (var i in filrouter) {
            let vallArr = filrouter[i];      //获取路由中的键值对类型
            let type = vallArr[0];
            //判断请求类型
            if (type === 'get') {
                if (vallArr.length === 2) {
                    let fn = vallArr[1];
                    router.get(i, fn);
                } else {
                    let auth = vallArr[1];
                    let fn = vallArr[2];
                    router.get(i, auth, fn);
                }
            }
            else if (type === 'post') {
                if (vallArr.length === 2) {
                    let fn = vallArr[1];
                    router.post(i, fn);
                } else {
                    let auth = vallArr[1];
                    let fn = vallArr[2];
                    router.post(i, auth, fn);
                }
            }
            else if (type === 'put') {
                if (vallArr.length === 2) {
                    let fn = vallArr[1];
                    router.put(i, fn);
                } else {
                    let auth = vallArr[1];
                    let fn = vallArr[2];
                    router.put(i, auth, fn);
                }
            }
            else if (type === 'delete') {
                if (vallArr.length === 2) {
                    let fn = vallArr[1];
                    router.delete(i, fn);
                } else {
                    let auth = vallArr[1];
                    let fn = vallArr[2];
                    router.delete(i, auth, fn);
                }
            }
        }
    });
};

module.exports = () => {
    // 1、解决正确获得控制器文件夹路径
    let defaultControlleDir = __dirname;

    let full = fillrouter(defaultControlleDir);

    registerRouter(full);

    return router.routes();
}
